<?php
/**
 * Created by PhpStorm.
 * User: an
 * Date: 2015/10/13
 * Time: 14:35
 */
namespace Shop\Controller;


use Admin\Api\InternationalAlipayNotifyApi;
use Admin\Api\OrdersPaycodeApi;
use Common\Api\PayOrderApi;
use Shop\Api\OrdersApi;
use Shop\Model\OrdersModel;
use Admin\Api\ConfigApi;
use Think\Log;

class GAlipayController extends ShopController{

    private  $alipay_config;



    /**
     * 准备支付
     */
    public function pay(){
        //Partner：2088101122136241  Key:760bdzec6y9goq7ctyx96ezkz78287de
        $pay_code = $this->_get("code",'','参数缺失!');
        $pay_name = $this->_get("name",'');
        $pay_desc = $this->_get("desc",'');
        $key = $this->_get("key",'','您的订单存在风险(-1)!');
        $total_price = $this->_get("total_price",'');
        addLog("GAlipay/pay",$_GET,$_POST,"[调试]",true);
        $pay_name = urldecode($pay_name);
        $pay_desc = urldecode($pay_desc);

        $encode = urlencode($pay_code.$pay_name.$pay_desc.$total_price);

        addLog("GAlipay/pay url encode ",$encode,$encode,"[调试]",true);

        $encode = md5(strtolower($encode));

        addLog("GAlipay/pay md5 ",$encode,$encode,"[调试]",true);

        if($total_price <= 0){
            $this->error("您的订单存在风险(0)!");
        }

        if(pay_encrypt_md5($encode) != $key){
            $this->error("您的订单存在风险(1)!");
        }

//        $this->assign('pay_name',$pay_name);
//        $this->assign('pay_desc',$pay_desc);
//        $this->assign('pay_code',$paycode);
//        $this->assign('rmb_fee',$total_price);

        $pay_id = explode("P",$pay_code);
        if(count($pay_id) < 2){
            $this->error("您的订单存在风险(2)!");
        }
        $pay_id = $pay_id[1];

        $result = apiCall(OrdersPaycodeApi::GET_INFO,array(array('id'=>$pay_id)));

        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
            $this->error("您的订单存在风险(3)!");
        }


        if($result['info']['pay_money'] != $total_price){
            $this->error("您的订单存在风险(4)!");
        }

        $out_trade_no = $pay_code;
        $subject = $pay_name;
        $body = $pay_desc;
        $rmb_fee = $total_price;

        //测试时
//        $rmb_fee = 0.07;

        /**************************请求参数**************************/
        //支付类型
        //$payment_type = "1";
        //必填，不能修改
        //服务器异步通知页面路径
        $notify_url = $this->alipay_config['notify_url'];// "http://demo001.itboye.com/index.php/notify";
        //需http://格式的完整路径，不能加?id=123这类自定义参数

        //页面跳转同步通知页面路径
        $return_url = $this->alipay_config['return_url']; //"http://192.168.0.100/oschina/index.php/Api/Alipay/return_url";
        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/

        //商户订单号
        $currency = 'USD';
        //付款金额
//        $total_fee =0.01;
        //商品展示地址
        //$show_url = $_POST['WIDshow_url'];
        //需以http://开头的完整路径，例如：http://www.商户网址.com/myorder.html

        //防钓鱼时间戳
        //$anti_phishing_key = "";
        //若要使用请调用类文件submit中的query_timestamp函数

        //客户端的IP地址
        //$exter_invoke_ip = "";
        //非局域网的外网IP地址，如：221.0.0.1
        /************************************************************/
        //构造要请求的参数数组，无需改动
        $parameter = array(
            "service" => "create_forex_trade",
            "partner" => trim($this->alipay_config['partner']),
            "notify_url" => $notify_url,
            "return_url" => $return_url,
            "out_trade_no" => $out_trade_no,
            "currency"	=> $currency,
            "subject" => $subject,
            //"total_fee" => $total_fee,
            "rmb_fee" => $rmb_fee,
            "body" => $body,
            "_input_charset" =>'utf-8'
        );


        addLog("GAlipay/add",$parameter,"","[调试]",true);

        //建立请求
        $alipaySubmit = new \AlipaySubmit($this->alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter, "get", "");
        echo $html_text;


    }


    /**
     * 构造函数
     */
    public function __construct(){
        parent::__construct();
        $this->getConfig();
        $this->alipay_config = $this->getAlipayConfig();
        addLog("GAlipay/__construct",$this->alipay_config,"","[调试]",true);
        //引入支付官方sdk
        vendor('alipay_submit',APP_PATH.'Api/Vendor/InternationalAlipay/','.class.php');

    }


    public function getAlipayConfig(){
        //↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
        //合作身份者id，以2088开头的16位纯数字
//        $alipay_config['partner']		= C('ALIPAY_API.TEST_INTERNATIONAL_ALIPAY_PARTNER');
//
//        //安全检验码，以数字和字母组成的32位字符
//        $alipay_config['key']			=  C('ALIPAY_API.TEST_INTERNATIONAL_ALIPAY_KEY');

        $alipay_config['partner']		= C('ALIPAY_API.INTERNATIONAL_ALIPAY_PARTNER');

        //安全检验码，以数字和字母组成的32位字符
        $alipay_config['key']			=  C('ALIPAY_API.INTERNATIONAL_ALIPAY_KEY');


        //↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

        $alipay_config['return_url'] = C('ALIPAY_API.INTERNATIONAL_ALIPAY_RETURN_URL');
        //After the payment transaction is done
        //Notification URL
        $alipay_config['notify_url'] = C('ALIPAY_API.INTERNATIONAL_ALIPAY_NOTIFY_URL');

        //签名方式 不需修改
        $alipay_config['sign_type']    = strtoupper('MD5');

        //字符编码格式 目前支持 gbk 或 utf-8
        $alipay_config['input_charset']= strtolower('utf-8');

        //ca证书路径地址，用于curl中ssl校验
        //请保证cacert.pem文件在当前文件夹目录中
        $alipay_config['cacert']    = getcwd().'\\cacert.pem';

        //访问模式,根据自己的服务器是否支持ssl访问，若支持请选择https；若不支持请选择http
        $alipay_config['transport']    = 'http';

        return $alipay_config;
    }


    /**
     * 支付宝同步请求此支付回调
     * 支付成功
     */
    public function return_url(){
        //订单号
        $out_trade_no =  $_GET['out_trade_no'];
        addLog("GAlipay/return_url",$_GET,$_POST,"国际支付同步返回!");
        $this->clearCartItemCache();
        $this->assign('out_trade_no',$out_trade_no);
        //只有在测试时取消注释
//        (new PayOrderApi())->success($out_trade_no,OrdersModel::PAY_TYPE_ALIPAY);
        $this->theme($this->themeType)->display();
    }

    /**
     * 从数据库中取得配置信息
     */
    protected function getConfig() {
        $config = S('config_' . session_id() . '_' . session("uid"));
        //dump($config);
        if ($config === false) {
            $map = array();
            $fields = 'type,name,value';
            $result = apiCall(ConfigApi::QUERY_NO_PAGING, array($map, false, $fields));
            if ($result['status']) {
                $config = array();

                if (is_array($result['info'])) {
                    foreach ($result['info'] as $value) {
                        $config[$value['name']] = $this -> parse($value['type'], $value['value']);

                    }
                }
                //缓存配置300秒
                S("config_" . session_id() . '_' . session("uid"), $config, 300);
            } else {
                LogRecord('INFO:' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
                $this -> error($result['info']);
            }
        }
        //dump(session_id());

        // dump($config);
        C($config);
    }

    /**
     * 根据配置类型解析配置
     * @param  integer $type 配置类型
     * @param  string $value 配置值
     * @return array|string
     */
    private static function parse($type, $value) {
        switch ($type) {
            case 3 :
                //解析数组
                $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
                if (strpos($value, ':')) {
                    $value = array();
                    foreach ($array as $val) {
                        list($k, $v) = explode(':', $val,2);
                        $value[$k] = $v;
                    }
                } else {
                    $value = $array;
                }
                break;
        }
        return $value;
    }

}